package com.ruoyi.framework.datasource;

import com.alibaba.druid.filter.config.ConfigTools;

/**
 * Druid 加/解密密码工具
 *
 * @author yacong_liu
 * @version 1.0
 * @classname DruidPasswordEncrypt
 * @date 2022/2/8
 **/
public class DruidPasswordTools {

    public static void main(String[] args) throws Exception {
        String password = "rootadmin";
        forDefault(password);
        System.out.println("-------------------------------");
        forRandom(password);

        System.out.println("明文密码->>>: "+decryptRandom(
                "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIx+ciGInKwvBdcYr8RApgrSe+9tasjRcF6oK2l5YFpaVag9iImQzawZEk4g" +
                        "XP1uRg018Gp0g6uwcQO2hSZAO7MCAwEAAQ==",
                "i78B2dhqffpGnpOsRo3z/+qEJQh8isnSVp5tLY4EVttm5IjXGa1maXGB7ULKFsdnkwxqYDzVJWl0yMk3Oh//RA=="));
    }

    /**
     * 以随机公钥私钥加解密
     *
     * @param password 密码
     * @throws Exception
     */
    public static void forRandom(String password) throws Exception {
        String[] arr = ConfigTools.genKeyPair(512);
        System.out.println("privateKey:" + arr[0]);
        System.out.println("配置到Druid的publicKey->>>: " + arr[1]);
        System.out.println("配置到Druid的password->>>: " + ConfigTools.encrypt(arr[0], password));
    }

    /**
     * 以Druid configTools默认公钥私钥加解密
     *
     * @param password 密码
     * @throws Exception
     */
    public static void forDefault(String password) throws Exception {
        String encrypt = encryptDefault(password);
        String publicKey = ConfigTools.DEFAULT_PUBLIC_KEY_STRING;
        System.out.println("配置到Druid的publicKey->>>: " + publicKey);
        System.out.println("配置到Druid的password->>>: " + encrypt);
    }

    public static String encryptDefault(String password) throws Exception {
        // 采用Druid 自带的私钥加密
        return ConfigTools.encrypt(password);
    }

    public static String decryptDefault(String ciphertext) throws Exception {
        // 采用Druid自带的公钥解密
        return ConfigTools.decrypt(ciphertext);
    }

    /**
     * 传递公钥解密
     *
     * @param publicKey  公钥
     * @param ciphertext 密文
     * @return 明文密码
     * @throws Exception
     */
    public static String decryptRandom(String publicKey, String ciphertext) throws Exception {
        return ConfigTools.decrypt(publicKey, ciphertext);
    }

}
